package com.ml4ai.backend.services.impl;

import com.ml4ai.backend.domain.Task;
import com.ml4ai.backend.domain.base.BusinessType;
import com.ml4ai.backend.dto.TaskDTO;
import com.ml4ai.backend.repository.TaskRepo;
import com.ml4ai.backend.services.base.impl.BaseServiceImpl;
import com.ml4ai.backend.services.TaskService;
import com.ml4ai.backend.services.mappers.TaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Function;

/**
 * Created by uesr on 2018/9/9.
 */
@Service
@Transactional
public class TaskServiceImpl extends BaseServiceImpl<Task, TaskDTO> implements TaskService {

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    TaskRepo taskRepo;

    @Override
    public Function<Task, TaskDTO> getConvertEntity2DTOFunction() {
        return taskMapper::e2d;
    }

    @Override
    public Function<TaskDTO, Task> getConvertDTO2EntityFunction() {
        return taskMapper::d2e;
    }

    @Override
    public JpaRepository<Task, Long> getRepository() {
        return taskRepo;
    }

    @Override
    public String genCode(BusinessType businessType) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentTimestamp = format.format(new Date());
        String bizNo;
        int init = 0;
        String pre;
        switch (businessType) {
            case IntraCityDistribution:
                pre = "ICD-";
                break;
            default:
                pre = businessType.toString() + "-";
        }
        while (true) {
            bizNo = pre + currentTimestamp + "-" + String.format("%06d", init);
            Task ls = taskRepo.findByBusinessCode(bizNo);
            if (ls == null) {
                return bizNo;
            }
        }
    }
}
